package com.cloudfun.campusshare.device.protocol.consumer;

import com.cloudfun.campusshare.common.constant.DeviceType;
import com.cloudfun.campusshare.common.constant.SysDictType;
import com.cloudfun.campusshare.device.protocol.response.BaseMessage;
import com.cloudfun.campusshare.device.protocol.response.TypeId;
import com.cloudfun.campusshare.entity.DeviceEntity;
import com.cloudfun.campusshare.repo.DeviceEntityRepo;
import com.cloudfun.campusshare.service.SysDictService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created by Huqin on 2020/4/23
 */
@Slf4j
@Component
public class DeviceTypeIdConsumer implements DeviceMessageConsumer {

    @Autowired
    private SysDictService sysDictService;

    @Autowired
    private DeviceEntityRepo deviceEntityRepo;

    @Override
    public boolean support(Class<?> clazz) {
        return TypeId.class.isAssignableFrom(clazz);
    }

    @Override
    public void doConsumer(BaseMessage message, String deviceName) {
        TypeId typeId = (TypeId) message;
        Map<String, String> dictByType = sysDictService.getDictByType(SysDictType.TYPE_ID_DEVICE_TYPE);
        DeviceEntity deviceEntity = deviceEntityRepo.findByImei(deviceName);
        if (null == deviceEntity) {
            log.error("根据imei：{}找不到设备", deviceName);
            return;
        }
        String deviceType = dictByType.get(typeId.getTypeId().toLowerCase());
        String oldDeviceType = deviceEntity.getDeviceType();
        if (StringUtils.isBlank(deviceType)) {
            log.error("收到设备typeId消息: {}，找不到设备类型", typeId.getTypeId());
            return;
        }
        if (!oldDeviceType.equals(deviceType)) {
            log.info("收到设备typeId消息: {}，修改设备类型。from: {}, to: {}", typeId.getTypeId(), oldDeviceType, deviceType);
            deviceEntity.setDeviceType(deviceType);
            DeviceType type = DeviceType.getDeviceTypeByName(deviceType);
            if (null != type) {
                deviceEntity.setProductType(type.getProductType());
            }
            deviceEntityRepo.save(deviceEntity);
        }
    }
}
